import store from "@/store/store";
import { baseUrl } from "@/config/config";
import { platform } from "@/util/platform";
import { auth } from "@/model/authToLogin/auth";
import { request, catchException } from "@/util/request";

function setNavBarOpacity(e: Page.IScrollNum, color: string): Page.IScrollRes {
  let opacity = e.scrollTop / 100;
  if (e.scrollTop < 20) opacity = 0;
  if (opacity > 1) opacity = 1;
  return {
    color: `rgba(${color}, ${opacity})`,
    opacity,
  };
}
function stringifyParams(params: Page.pageQuery) {
  let arr: string[] = [];
  for (let k in params) {
    const isNullish = params[k] ?? "nullish";
    if (isNullish !== "nullish") {
      const str = `${encodeURIComponent(k)}=${encodeURIComponent(params[k])}`;
      arr.push(str);
    }
  }
  return arr.join("&");
}
function setPageStyle(styles: Page.IStyles = {}): string {
  const { programState, globalState, gameState } = store;
  const { pageColor } = globalState;
  const { statusBarHeight, titleBarHeight, windowHeight, safeAreaBottom } = programState;
  const titleNavBarHeight = `${statusBarHeight + titleBarHeight}px`;
  const { warning_color, theme_color, theme_text_color, error_color } = gameState?.material;
  const defaultPageStyle = {
    "--xThemeColor": theme_color || "#5494E8",
    "--xThemeTextColor": theme_text_color || "#5494E8",
    "--xThemeErrorColor": error_color || "#ee2929",
    "--xThemeAlertColor": warning_color || "#f69f39",
    "--xTitleNavBarHeight": titleNavBarHeight,
  };
  // if (pageColor.is_gray) defaultPageStyle["filter"] = "grayscale(100%)";
  if (windowHeight === safeAreaBottom) {
    defaultPageStyle["padding-bottom"] = styles.noSafeAreaPagePadding || "15px";
  }
  styles = { ...defaultPageStyle, ...styles };
  delete styles?.noSafeAreaPagePadding;
  if (platform === "H5") styles["--xTitleNavBarHeight"] = "0px";
  const styleList: string[] = [];
  for (const key in styles) styleList.push(`${key}:${styles[key]}`);
  return styleList.join(";");
}
function setPagePadding(styles: Page.IStyles = {}): string {
  const { programState, globalState } = store;
  const { pageColor } = globalState;
  const { statusBarHeight, titleBarHeight, windowHeight, safeAreaBottom } = programState;
  const titleNavBarHeight = `${statusBarHeight + titleBarHeight}px`;
  const defaultPageStyle = {
    "--xTitleNavBarHeight": titleNavBarHeight,
  };
  // if (pageColor.is_gray) defaultPageStyle["filter"] = "grayscale(100%)";
  if (windowHeight === safeAreaBottom) {
    defaultPageStyle["padding-bottom"] = styles.noSafeAreaPagePadding || "15px";
  }
  styles = { ...defaultPageStyle, ...styles };
  delete styles?.noSafeAreaPagePadding;
  if (platform === "H5") styles["--xTitleNavBarHeight"] = "0px";
  const styleList: string[] = [];
  for (const key in styles) styleList.push(`${key}:${styles[key]}`);
  return styleList.join(";");
}
class Countdown {
  private timer: any;
  private time: number;
  private format: string;
  private callback: (v: string) => void;
  constructor() {
    this.time = 0;
    this.timer = 0;
    this.format = "";
    this.callback = (v: string) => {};
  }
  public start({ time, format, callback }: ICountdownProps): void {
    if (time <= 0) {
      console.log("countdown time 必须大于 0");
      return;
    } else {
      this.time = time;
    }
    this.format = format;
    this.callback = callback;
    this.clockStart();
  }
  public stop() {
    clearTimeout(this.timer);
  }
  private clockStart(): void {
    let timeStr = this.formatter();
    this.timer = setTimeout(() => this.clockStart(), 1000);
    this.callback(timeStr);
    this.time -= 1000;
    if (this.time < 0) this.stop();
  }
  private formatter(): string {
    const obj = {
      DD: Math.floor(this.time / (1000 * 60 * 60 * 24)),
      HH: Math.floor((this.time / (1000 * 60 * 60)) % 24),
      mm: Math.floor((this.time / (1000 * 60)) % 60),
      ss: Math.floor((this.time / 1000) % 60),
    };
    return this.format.replace(/([a-zA-Z]+)/g, (match) => {
      return match === "DD" ? obj[match] : obj[match] < 10 ? `0${obj[match]}` : obj[match];
    });
  }
}
function fileUrl(path: string) {
  path = path || "";
  return path?.includes(":/") ? path : `${baseUrl}uploads/${path}`;
}
function materialUrl(name: string) {
  name ||= "";
  const { gameState } = store;
  let baseMaterial = gameState.material?.resource_path;
  if (!baseMaterial) {
    const material = JSON.parse(uni.getStorageSync("material") || "{}");
    if (material.resource_path) gameState.material = material;
    baseMaterial = material.resource_path;
  }
  return name?.includes(":/") ? name : `${baseUrl}uploads/${baseMaterial}/${name}`;
}
function valueType(v: any): string {
  const str = Object.prototype.toString.call(v);
  const typeArr = str.match(/\[object (.*?)\]/) || [];
  return typeArr[1].toLowerCase();
}
function formatDate(dateTime: Date, format: string) {
  const obj = {
    yyyy: dateTime.getFullYear(),
    yy: dateTime.getFullYear() % 100 || "00",
    M: dateTime.getMonth() + 1,
    d: dateTime.getDate(),
    H: dateTime.getHours(),
    h: dateTime.getHours() % 12,
    m: dateTime.getMinutes(),
    s: dateTime.getSeconds(),
    w: ["日", "一", "二", "三", "四", "五", "六"][dateTime.getDay()],
  };
  return format.replace(/([a-zA-Z]+)/g, (match) => {
    return match.length === 2 && match !== "yy"
      ? ("0" + obj[match.slice(1)]).slice(-2)
      : obj[match];
  });
}
function previewImg(props: IPreviewImgProps) {
  const urls = props.urls.reduce((memo, url) => [...memo, fileUrl(url)], [] as string[]);
  const current = urls[0];
  uni.previewImage({ current, urls });
}
function parseUrl(url: string) {
  let params = { url: "" };
  params.url = url.split("?", 1).toString();
  const query = url.substring(url.indexOf("?") + 1).split("&");
  for (let i = 0, len = query.length; i < len; i++) {
    const str = decodeURIComponent(query[i]);
    if (!str.includes("=")) continue;
    const kv = str.split("=");
    params[kv[0]] = kv[1];
  }
  return params;
}
function parseWebUrl(url: string) {
  let params = {} as { [propName: string]: string };
  const parsedUrl = new URL(url);
  parsedUrl.searchParams.forEach((value, key) => (params[key] = value));
  return params;
}
export {
  setNavBarOpacity,
  setPageStyle,
  setPagePadding,
  Countdown,
  fileUrl,
  valueType,
  formatDate,
  materialUrl,
  previewImg,
  stringifyParams,
  parseUrl,
  parseWebUrl,
};
